<template>
  <div>
    <el-tabs v-model="activeName" @tab-click="handleClick" class="bg-in-stock">
      <el-tab-pane label="结算单列表" name="settlementList">
        <en-table-layout :tableData="settlementTableData.data" :loading="loading">
          <div slot="toolbar" class="inner-toolbar">
            <div class="toolbar-btns">
            </div>
            <div class="toolbar-search">
              <en-table-search @search="searchEvents" @advancedSearch="advancedSearchEvents" placeholder="请输入结算单编号"
                advanced advancedWidth="465">
                <template slot="advanced-content">
                  <el-form ref="advancedForms" :model="advancedForms" label-width="90px">
                    <el-form-item label="供应商" prop="supplier_id">
                      <el-select v-model="advancedForms.supplier_id">
                        <el-option v-for="item in supplierList" :key="item.id" :label="item.custom_name"
                          :value="item.id" />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="时间">
                      <el-date-picker v-model="advancedForms.purchasePlan_time_range" type="daterange" align="center"
                        :editable="false" unlink-panels :clearable="false" :default-time="['00:00:00', '23:59:59']"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" value-format="timestamp"
                        :picker-options="{ disabledDate(time) { return time.getTime() - 1 >= new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()).getTime() + 86400000 - 1 }, shortcuts: MixinPickerShortcuts }">
                      </el-date-picker>
                    </el-form-item>
                  </el-form>
                </template>
              </en-table-search>
            </div>
          </div>

          <template slot="table-columns">
            <el-table-column prop="sn" label="结算单编号">
              <template slot-scope="scope">
                <router-link
                  v-if="checkPermission(['settlement'])"
                  style="color: #409eff;"
                  :to="{ name: 'settlementDeatil', params: { id: scope.row.id } }">
                  {{ scope.row.sn }}
                </router-link>
                <span v-else>{{scope.row.sn}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="end_time" label="结算时间">
              <template slot-scope="scope">{{ scope.row.end_time | unixToDate }}</template>
            </el-table-column>
            <el-table-column prop="supplier_name" label="供应商名称" />
            <el-table-column prop="create_time" label="制单日期">
              <template slot-scope="scope">{{ scope.row.create_time | unixToDate }}</template>
            </el-table-column>
            <el-table-column prop="creator" label="制单人" />
            <el-table-column prop="total_price" label="结算金额">
              <template slot-scope="scope">¥{{ scope.row.total_price }}</template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template slot-scope="scope">
                <el-button v-if="checkPermission(['supplierSettlement:cancel'])" size="mini"
                  @click="handleCancellation(scope.row)">取消</el-button>
                <el-button v-if="checkPermission(['supplierSettlement:print'])" type="primary" size="mini"
                  @click="handlePrintSettlementListDialog(scope.row)">打印</el-button>
              </template>
            </el-table-column>
          </template>

          <el-pagination v-if="tableData" slot="pagination" @size-change="handlePageSizeChange"
            @current-change="handlePageCurrentChange" :current-page="tableData.page_no" :page-sizes="[10, 20, 50, 100]"
            :page-size="tableData.page_size" layout="total, sizes, prev, pager, next, jumper"
            :total="tableData.data_total">
          </el-pagination>
        </en-table-layout>
      </el-tab-pane>
      <el-tab-pane label="未结算采购单列表" name="purchaseWarehousing">
        <en-table-layout :tableData="tableData.data" :loading="loading" @selection-change="handleSelectionChange">
          <div slot="toolbar" class="inner-toolbar">
            <div class="toolbar-btns">
              <el-button size="mini" v-if="checkPermission(['supplierSettlement:add'])" type="primary"
                @click="handleGeneratePurchaseWarehousing">生成结算单</el-button>
            </div>
            <div class="toolbar-search">
              <en-table-search @search="searchEvent" @advancedSearch="advancedSearchEvent" placeholder="请输入入库单号" advanced
                advancedWidth="465">
                <template slot="advanced-content">
                  <el-form ref="advancedForm" :model="advancedForm" label-width="90px">
                    <el-form-item label="所属部门">
                      <el-cascader v-model="advancedForm.dept_id" :options="deptList" :props="{
                        label: 'name',
                        value: 'id',
                        emitPath: false,
                        checkStrictly: true
                      }" clearable></el-cascader>
                    </el-form-item>
                    <el-form-item label="供应商">
                      <el-select v-model="advancedForm.supplier_id">
                        <el-option v-for="item in supplierList" :key="item.id" :label="item.custom_name"
                          :value="item.id" />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="状态">
                      <el-select v-model="advancedForm.status">
                        <el-option key="NotSubmit" label="未提交" value="NotSubmit" />
                        <el-option key="Submit" label="已提交" value="Submit" />
                        <el-option key="AuditPass" label="审核通过" value="AuditPass" />
                        <el-option key="AuditReject" label="审核驳回" value="AuditReject" />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="时间">
                      <el-date-picker v-model="advancedForm.purchasePlan_time_range" type="daterange" align="center"
                        :editable="false" unlink-panels :clearable="false" :default-time="['00:00:00', '23:59:59']"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" value-format="timestamp"
                        :picker-options="{ disabledDate(time) { return time.getTime() - 1 >= new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()).getTime() + 86400000 - 1 }, shortcuts: MixinPickerShortcuts }">
                      </el-date-picker>
                    </el-form-item>
                  </el-form>
                </template>
              </en-table-search>
            </div>
          </div>

          <template slot="table-columns">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="sn" label="入库单编号">
              <template slot-scope="scope">
                <router-link
                  v-if="checkPermission(['purchaseWarehousing'])"
                  style="color: #409eff;"
                  :to="{ name: 'purchaseWarehousingDetail', params: { id: scope.row.id } }">
                  {{ scope.row.sn }}
                </router-link>
                <span v-else>{{scope.row.sn}}</span>
              </template>
            </el-table-column>
            <el-table-column label="入库日期">
              <template slot-scope="scope">{{ scope.row.entry_time | unixToDate }}</template>
            </el-table-column>
            <el-table-column prop="dept_name" label="所属部门" />
            <el-table-column prop="warehouse_name" label="仓库" />
            <el-table-column prop="supplier_name" label="供应商" />
            <el-table-column prop="plate_number" label="车牌号" />
            <el-table-column prop="handled_by_name" label="经手人" />
            <el-table-column prop="audit_by" label="审核人" />
          </template>

          <el-pagination v-if="tableData" slot="pagination" @size-change="handlePageSizeChange"
            @current-change="handlePageCurrentChange" :current-page="tableData.page_no" :page-sizes="[10, 20, 50, 100]"
            :page-size="tableData.page_size" layout="total, sizes, prev, pager, next, jumper"
            :total="tableData.data_total">
          </el-pagination>
        </en-table-layout>
      </el-tab-pane>
    </el-tabs>

    <el-dialog title="供应商结算单" :visible.sync="dialogVisible" width="850px" center>
      <el-button size="mini" type="primary" @click="handlePrintPurchasePlan" class="print">打印</el-button>
      <div id="deliverySheet" style="width:810px">
        <div class="tips-t">
          <div>
            供应商:{{ settlementForm.supplier_name }}
          </div>
          <div>
            结算日期:{{ settlementForm.start_time | unixToDateStr }} 至 {{ settlementForm.end_time | unixToDateStr }}
          </div>
          <div>
            编号:{{ settlementForm.sn }}
          </div>
        </div>
        <el-table :data="settlementForm.item_list" border :cell-style="{ textAlign: 'center' }"
          :header-cell-style="{ textAlign: 'center', background: '#f4f4f4' }"
          style="width: 100%; margin:auto;margin-top: 20px;">
          <el-table-column label="商品编号" width="159">
            <template slot-scope="scope">
              {{ scope.row.product_sn }}
            </template>
          </el-table-column>
          <el-table-column label="商品名称" width="150">
            <template slot-scope="scope">
              {{ scope.row.product_name }}
            </template>
          </el-table-column>
          <el-table-column label="规格型号" width="150">
            <template slot-scope="scope">
              {{ scope.row.product_specification }}
            </template>
          </el-table-column>
          <el-table-column label="单价" width="100">
            <template slot-scope="scope">
              ¥{{ scope.row.product_price }}
            </template>
          </el-table-column>
          <el-table-column label="数量" width="150">
            <template slot-scope="scope">
              {{ scope.row.product_num }}
            </template>
          </el-table-column>
          <el-table-column label="合价" width="100">
            <template slot-scope="scope">
              ¥{{ scope.row.total_price }}
            </template>
          </el-table-column>
        </el-table>
        <div class="tips-t">
          <div>
            制单日期: {{ settlementForm.create_time | unixToDate }}
          </div>
          <div></div>
          <div>
            制单人: {{ settlementForm.creator }}
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as API_Purchase from '@/api/purchase'
import { Foundation } from '~/ui-utils'
import * as API_Setting from '@/api/setting'
import * as API_Supplier from '@/api/supplier'
import * as API_BasicSetting from '@/api/basicSetting'
import Print from 'print-js'
export default {
  name: 'supplierSettlement',
  data() {
    return {
      multipleSelection: [],
      supplierList: [],
      deptList: [],
      // 列表loading状态
      loading: false,
      // 列表参数
      params: {
        page_no: 1,
        page_size: 10,
        supplier_settlement_flag: false,
        status: 'AuditPass'
      },
      settlementParams: {
        page_no: 1,
        page_size: 10
      },
      // 高级搜索数据
      advancedForm: {},
      advancedForms: {},
      // 列表数据
      tableData: '',
      settlementTableData: '',
      dialogVisible: false,
      activeName: 'settlementList',
      settlementForm: {}
    }
  },
  mounted() {
    this.GET_PurchaseWarehousingList()
    this.GET_SupplierSettlement()
    this.GET_DeptList()
    this.GET_SupplierList()
  },
  methods: {
    handlePrintSettlementListDialog(row) {
      this.GET_SettlementDetail(row.id)
    },
    GET_SettlementDetail(id) {
      API_Supplier.getsupplierSettlementInfo(id).then(response => {
        this.settlementForm = response
        this.dialogVisible = true
      })
    },
    /** 获取供应商 */
    GET_SupplierList() {
      API_BasicSetting.getSupplierListAll().then(response => {
        this.supplierList = response
      })
    },
    /** 搜索事件触发 */
    searchEvents(data) {
      this.settlementParams = {
        ...this.settlementParams,
        sn: data
      }
      Object.keys(this.advancedForms).forEach((key) => delete this.params[key])
      this.settlementParams.page_no = 1
      this.GET_SupplierSettlement()
    },
    /** 高级搜索事件触发 */
    advancedSearchEvents() {
      this.settlementParams = {
        ...this.settlementParams,
        ...this.advancedForms
      }
      delete this.settlementParams.start_time
      delete this.settlementParams.end_time
      if (this.advancedForms.purchasePlan_time_range) {
        this.settlementParams.start_time = parseInt(Number(this.advancedForms.purchasePlan_time_range[0]) / 1000)
        this.settlementParams.end_time = parseInt(Number(this.advancedForms.purchasePlan_time_range[1]) / 1000)
      }
      delete this.settlementParams.purchasePlan_time_range
      this.settlementParams.page_no = 1
      this.GET_SupplierSettlement()
    },
    /** 打印对账详情 */
    handlePrintPurchasePlan() {
      Print({
        printable: 'deliverySheet',
        type: 'html',
        targetStyles: ['*'],
        ignoreElements: ['no-logs', 'goods-image', 'no-btn']
      })
    },
    handleCancellation(row) {
      this.$confirm('确定要取消当前结算单吗？', '提示', { type: 'warning' }).then(() => {
        API_Supplier.deletesupplierSettlementCancel(row.id).then(() => {
          this.$message.success('取消成功！')
          this.GET_SupplierSettlement()
          this.GET_PurchaseWarehousingList()
        })
      }).catch(() => { })
    },
    GET_SupplierSettlement() {
      this.loading = true
      API_Supplier.getsupplierSettlement(this.settlementParams).then(response => {
        this.loading = false
        this.settlementTableData = response
      }).catch(() => { this.loading = false })
    },
    handleGeneratePurchaseWarehousing() {
      if (!this.multipleSelection || !this.multipleSelection.length) return this.$message.error('请先选择！')
      this.$confirm('确定要这些生成结算单吗？', '提示', { type: 'warning' }).then(() => {
        const ids = this.multipleSelection.map(item => item.id)
        API_Supplier.adderpSupplierSettlement({ warehouse_entry_ids: ids }).then(() => {
          this.$message.success('生成成功！')
          this.GET_PurchaseWarehousingList()
          this.GET_SupplierSettlement()
        })
      }).catch(() => { })
    },
    /** 获取部门 */
    GET_DeptList() {
      API_Setting.getDeptList().then(response => {
        this.deptList = Foundation.buildTree(response, '0')
      })
    },
    /** 搜索事件触发 */
    searchEvent(data) {
      this.params = {
        ...this.params,
        sn: data
      }
      Object.keys(this.advancedForm).forEach((key) => delete this.params[key])
      this.params.page_no = 1
      this.GET_PurchaseWarehousingList()
    },
    /** 高级搜索事件触发 */
    advancedSearchEvent() {
      this.params = {
        ...this.params,
        ...this.advancedForm
      }
      delete this.params.start_time
      delete this.params.end_time
      if (this.advancedForm.purchasePlan_time_range) {
        this.params.start_time = parseInt(Number(this.advancedForm.purchasePlan_time_range[0]) / 1000)
        this.params.end_time = parseInt(Number(this.advancedForm.purchasePlan_time_range[1]) / 1000)
      }
      delete this.params.purchasePlan_time_range
      this.params.page_no = 1
      this.GET_PurchaseWarehousingList()
    },
    /** 获取采购入库列表 */
    GET_PurchaseWarehousingList() {
      this.loading = true
      API_Purchase.getPurchaseWarehousingList(this.params).then(response => {
        this.loading = false
        this.tableData = response
      }).catch(() => { this.loading = false })
    },
    /** 多选改变 */
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    /** 分页大小发生改变 */
    handlePageSizeChange(size) {
      this.params.page_size = size
      this.GET_PurchaseWarehousingList()
    },

    /** 分页页数发生改变 */
    handlePageCurrentChange(page) {
      this.params.page_no = page
      this.GET_PurchaseWarehousingList()
    }
  }
}
</script>

<style type="text/scss" lang="scss" scoped>
.print {
  margin-left: 750px;
}

.tips-t {
  display: flex;
  padding: 10px 0;

  div {
    flex: 1;
    text-align: center;
  }
}

.tips-f {
  padding: 20px 0;
}

.face-image {
  display: block;
  width: 50px;
  height: 50px;
  margin: 0 auto;
}

/deep/ .el-dialog__body {
  padding: 10px 20px;
}

.bg-in-stock {
  background-color: #fff;
  margin: 10px;
  padding: 25px;
}
</style>
